﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class TestPlayer : MonoBehaviour {
	
	public Animator anim;
	
	public GameObject daggerskill1fx;
    
	private Vector2 dir = Vector2.zero;
	protected bool isMove = false;
	
	private Transform camTrans;
	private Vector3 camOffset;
	public CharacterController ctrl;

	private float targetBlend;
	private float curBlend;
	
	public Vector2 Dir{
		get{ return dir; }
		set{
			if (value == Vector2.zero){
				isMove = false;
			}
			else{
				isMove = true;
			}

			dir = value;
		}
	}
	
	private void Start(){
		camTrans = Camera.main.transform;
		camOffset = transform.position - camTrans.position;
	}
	
	private void Update(){
		#region Input
        
		float h = Input.GetAxis("Horizontal");
		float v = Input.GetAxis("Vertical");
		Vector2 _dir = new Vector2(h, v).normalized;
		if (_dir != Vector2.zero){
		    Dir = _dir;
		    SetBlend(Constants.BlendMove);
		}
		else{
		    Dir = Vector2.zero;
		    SetBlend(Constants.BlendIdle);
		}

		#endregion

		if (curBlend != targetBlend){
			UpdateMixBlend();
		}

		if (isMove){
			//设置方向
			SetDir();

			//产生移动
			SetMove();

			//相机跟随
			SetCam();
		}
	}
	
	private void SetDir(){
		float angle = Vector2.SignedAngle(Dir, new Vector2(0, 1)) + camTrans.localEulerAngles.y;
		Vector3 eulerAngles = new Vector3(0, angle, 0);
		transform.localEulerAngles = eulerAngles;
	}

	private void SetMove(){
		ctrl.Move(transform.forward * Time.deltaTime * Constants.PLayerMoveSpeed);
	}

	public void SetCam(){
		if (camTrans != null){
			camTrans.position = transform.position - camOffset;
		}
	}

	private void UpdateMixBlend(){
		if (Mathf.Abs(curBlend - targetBlend) < Constants.AccelerSpeed * Time.deltaTime){
			curBlend = targetBlend;
		}
		else if (curBlend > targetBlend){
			curBlend -= Constants.AccelerSpeed * Time.deltaTime;
		}
		else if (curBlend < targetBlend){
			curBlend += Constants.AccelerSpeed * Time.deltaTime;
		}

		anim.SetFloat("Blend", curBlend);
	}
	
	public void SetBlend(float blend){
		targetBlend = blend;
	}

	public void ClickSkill1Btn(){
		anim.SetInteger("Action", 1);
		daggerskill1fx.gameObject.SetActive(true);
		StartCoroutine(Delay());
	}

	IEnumerator Delay(){
		yield return new WaitForSeconds(0.9f);
		anim.SetInteger("Action", -1);
		daggerskill1fx.gameObject.SetActive(false);
	}
	
}
